//'use strict';
var Chat = function (sok){
	this.sok = sok;
};
// 发送消息
Chat.prototype.sendMsg = function(room,text){
	var message = {room:room,text:text};
	this.sok.emit('message',message);
};
// 切换房间
Chat.prototype.changeRoom = function(room){
	this.socket.emit('join',{newRoom:room});
};
// 处理命令
Chat.prototype.processCommand = function(command){
	var words = command.split(' ');
	var command = words[0].substring(1,words[0].length).toLowerCase();
	var message = false;
	switch(command){
		case 'join':
			words.shift();
			var room = words.join(' ');
			this.changeRoom(room);
			break;
		case 'nick':
			words.shift();
			var name = words.join(' ');
			this.sok.emit('nameAttempt',name);
			break;
		default:
			message = 'Unresognized command.';
			break;
	}
	return message;
}

function divEscapedContentElement(msg){
	return $('<div/>').text(msg);
}

function divSystemContentElement(msg){
	return $('<div/>').html('<i>'+msg+'</i>');
}

function peocessUserInput(chatApp,sok){
	var msg = $('#send-msg').val();
	var sysMsg;
	// 如果第一个字符是斜杠则当作 命令来处理
	if(msg.charAt(0)=='/'){
		sysMsg = chatApp.processCommand(msg);
		if(sysMsg){
			$('#msg').append(divSystemContentElement(sysMsg));
		}
	} else{
		// 将消息推送给其他用户
		chatApp.sendMsg($('#curr-room').text(),msg);
		$('#msg').append(divEscapedContentElement(nick+': '+msg));
		$('#msg').scrollTop($('#msg').prop('scrollHeight'));
	}
	 $('#send-msg').val('');
}

var sok = io.connect();
var nick ;
$(function(){
	var chatApp = new Chat(sok);
	sok.on('nameResult',function(result){
		var msg = '';
		if(result.success){
			nick = result.name;
			msg = 'You are now known as '+result.name +'.';
		} else{
			msg = result.message;
		}
		$('#msg').append(divSystemContentElement(msg));
	});

	sok.on('joinResult',function(result){
		console.log(result)
		$('#curr-room').text(result.room);
		$('#msg').append(divSystemContentElement('Room changed.'));
	});

	sok.on('message',function(msg){
		$('#msg').append(divEscapedContentElement(msg.text));
	});

	sok.on('rooms',function(rooms){
		$('#room-list').empty();
		console.log(rooms);
		for (var room in rooms) {
			room = room.substring(1,room.length);
			if(room != ''){
				$('#room-list').append(divEscapedContentElement(room))
			}
		}
		$('#room-list div').click(function(){
			chatApp.processCommand('/join'+$(this).text())
			$('#send-msg').focus();
		})
	});
	// setInterval(function(){
	// 	sok.emit('rooms');
	// },1000);
	$('#send-msg').focus();
	$('#send-btn').click(send);
	$('#send-msg').keydown(send);
	function send(e){
		if($('#send-msg').val()){
			if(e.type == 'keydown' && e.keyCode==13){
				peocessUserInput(chatApp,sok);
				return false;
			} else if(e.type == 'click'){
				peocessUserInput(chatApp,sok);
			}
		} else {
			return false;
		}
	}

})

